// Physical memory allocator, for user processes,
// kernel stacks, page-table pages,
// and pipe buffers. Allocates whole 4096-byte pages.

#include "types.h"
#include "param.h"
#include "memlayout.h"
#include "spinlock.h"
#include "riscv.h"
#include "defs.h"

void freerange(void *pa_start, void *pa_end);

extern char end[]; // first address after kernel.
                   // defined by kernel.ld.

struct run {
  struct run *next;
};

struct kmem{
  struct spinlock lock;
  struct run *freelist;
} ;

struct kmem kmems[NCPU];

void
kinit()
{
  // push_off();
  // printf("cpu is:%d",cpuid());
  // pop_off();
  for (int i = 0; i < NCPU; i++)
  {
  initlock(&kmems[i].lock, "kmem");
  }
  freerange(end, (void*)PHYSTOP);
}

void
freerange(void *pa_start, void *pa_end)
{
  char *p;
  p = (char*)PGROUNDUP((uint64)pa_start);
  for(; p + PGSIZE <= (char*)pa_end; p += PGSIZE)
    kfree(p);
}

// Free the page of physical memory pointed at by v,
// which normally should have been returned by a
// call to kalloc().  (The exception is when
// initializing the allocator; see kinit above.)
void
kfree(void *pa)
{
  struct run *r;

  if(((uint64)pa % PGSIZE) != 0 || (char*)pa < end || (uint64)pa >= PHYSTOP)
    panic("kfree");

  // Fill with junk to catch dangling refs.
  memset(pa, 1, PGSIZE);
  r = (struct run*)pa;

// 获得当前cpuid
  push_off();
  int i=cpuid();
  pop_off();

  acquire(&kmems[i].lock);
  r->next = kmems[i].freelist;
  kmems[i].freelist = r;
  release(&kmems[i].lock);
}





void *
kalloc(void)
{
  struct run *r;

  push_off(); 
  int cpu_id = cpuid(); 
  pop_off();
  acquire(&kmems[cpu_id].lock);
  r = kmems[cpu_id].freelist;
  if(r)
  {
    kmems[cpu_id].freelist = r->next;
    release(&kmems[cpu_id].lock);
  } 
  else
  {
    release(&kmems[cpu_id].lock);
    int t=0;
    cpu_id++;
    while(t<NCPU-1)
    {
      if(cpu_id==(NCPU))
        cpu_id=0;
      acquire(&kmems[cpu_id].lock);
      r = kmems[cpu_id].freelist;
      if(r)
      {
        kmems[cpu_id].freelist = r->next;
        release(&kmems[cpu_id].lock);
        break;
      }
      release(&kmems[cpu_id].lock);
      cpu_id++;
      t++;
    }
  }
  if(r)
    memset((char*)r, 5, PGSIZE); // fill with junk
  return (void*)r;
}